package com.yutel.app.elasticsearch;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpES {
	private final Logger log = LoggerFactory.getLogger(HttpES.class);

	public boolean c = true;
	public String baseUrl = "http://127.0.0.1:9200";

	public void start() {
		CloseableHttpClient httpclient = null;
		try {
			httpclient = HttpClients.createDefault();
			while (c) {
				list(httpclient);
			}
			httpclient.close();
		} catch (Exception e) {
			log.error("ex", e);
			try {
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
			}
		}
	}

	public void list(CloseableHttpClient httpclient) {
		String info = "{\"_source\":{\"includes\":[\"_id\"]},\"query\":{\"bool\":{\"must_not\":{\"exists\":{\"field\":\"routing\"}}}},\"sort\":[],\"from\":0,\"size\":100}";
		try {
			String url = "/tbmrundata1g/doc/_search?pretty";
			HttpPost post = new HttpPost(baseUrl + url);
			post.addHeader("Content-Type", "application/json;charset=UTF-8");
			post.setEntity(new StringEntity(info));
			CloseableHttpResponse response = httpclient.execute(post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity he = response.getEntity();
				String res = EntityUtils.toString(he, "UTF-8");
				response.close();
				JSONObject json = new JSONObject(res);
				JSONArray jsoa = json.getJSONObject("hits")
						.getJSONArray("hits");
				log.info("length={}", jsoa.length());
				if (jsoa.length() < 1) {
					c = false;
				}
				for (int i = 0; i < jsoa.length(); i++) {
					JSONObject j = jsoa.getJSONObject(i);
					String id = j.getString("_id");
					upda(httpclient, id);
				}
			} else {
				log.error("StatusLine={}", response.getStatusLine());
			}
		} catch (Exception e) {
			log.error("ex", e);
		}

	}

	public void upda(CloseableHttpClient httpclient, String id) {
		String info = null;
		try {
			info = "{\"doc\":{\"routing\":\"" + id.substring(0, 22) + "\"}}";
			String url = "/tbmrundata1g/doc/" + id + "/_update";
			HttpPost post = new HttpPost(baseUrl + url);
			post.addHeader("Content-Type", "application/json;charset=UTF-8");
			post.setEntity(new StringEntity(info));
			CloseableHttpResponse response = httpclient.execute(post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity he = response.getEntity();
				info = EntityUtils.toString(he, "UTF-8");
				response.close();
			} else {
				log.error("StatusLine={}", response.getStatusLine());
			}
		} catch (Exception e) {
			log.error("ex", e);
		}
	}

}
